<?php
namespace app\wechat\traits;

use EasyWeChat\Factory;

trait Official
{
    protected $config;
    protected $app;

    public function __construct()
    {
        $option = get_option("wechat_official")['official'];
        $config = config("official.");
        $this->config = array_merge($option,$config);

    }

    /**
     * 微信网页授权登录
     * chenping
     * 375129701@qq.com
     * target_url: 授权才能访问的地址
     * callback：回调地址
     * small_program: 小程序登录，false未启用，true启用
     */
    public function login($target_url='',$callback='',$small_program=false)
    {
        if($callback) $this->config['oauth']['callback'] = $callback;
        $app =  Factory::officialAccount($this->config);
        //发起网页授权
        $oauth =$app->oauth;
        $user = session('wechat_user');

        // 未登录
        if (empty($user))
        {
            if($target_url)
            {
                session('target_url',$target_url);
                return $oauth->redirect();
            }
            return [
                "user"=>""
            ];
        }
        return [
            "user" => $user
        ];
    }


    /**
     * Notes:创建临时二维码
     * User: chenping
     * email: 375129701@qq.com
     * return mixed
     */
    protected function create_prcode($content='')
    {
        $config = config("official.");

        $this->config = array_merge($this->config,$config);

        $app = Factory::officialAccount($this->config);
        return $app->qrcode->temporary($content, 6 * 24 * 3600);
    }


    /**
     * Notes:获取二维码地址
     * User: chenping
     * email: 375129701@qq.com
     * return string
     */
    protected function get_prcode_url($content='')
    {
        $res = $this->create_prcode($content);
        $app = Factory::officialAccount($this->config);
        return $app->qrcode->url($res['ticket']);
    }
}